package com.cmbyc.todolist.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmbyc.todolist.VO.MatterAddVO;
import com.cmbyc.todolist.VO.MatterVO;
import com.cmbyc.todolist.VO.TimedTaskVO;
import com.cmbyc.todolist.constant.TodoListConstant;
import com.cmbyc.todolist.entity.Matter;
import com.cmbyc.todolist.exception.ToException;
import com.cmbyc.todolist.mapper.MatterMapper;
import com.cmbyc.todolist.service.MailService;
import com.cmbyc.todolist.service.MatterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmbyc.todolist.service.UserInfoService;
import com.cmbyc.todolist.utils.DateUtil;
import com.cmbyc.todolist.utils.Token.TokenUtil;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * <p>
 * 事项表 服务实现类
 * </p>
 *
 * @author CYF
 * @since 2022-01-02
 */
@Service
public class MatterServiceImpl extends ServiceImpl<MatterMapper, Matter> implements MatterService {
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    MatterMapper matterMapper;
    @Autowired
    MailService mailService;
//    @Autowired
//    MatterService matterService;
    @Autowired
    ThreadPoolTaskExecutor taskExecutor;


    @Override
    public IPage<Matter> getList(MatterVO matterVO) {
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",0);
        if (!StringUtils.isEmpty(matterVO.getBId())){
            queryWrapper.eq("b_id",matterVO.getBId());
        }
        if (!StringUtils.isEmpty(matterVO.getTaskStatus())){
            queryWrapper.eq("task_status",0);
        }
//        queryWrapper.eq("create_by",TokenUtil.getTokenUserBId());
        queryWrapper.eq("create_by","1");
        Page<Matter> matterPage = new Page<>(matterVO.getPageNum(), matterVO.getPageSize());
        IPage<Matter> matterIPage = baseMapper.selectPage(matterPage , queryWrapper);
        matterIPage.setTotal(matterIPage.getRecords().size());
        return matterIPage;
    }

    @Override
    public void addInfo(MatterAddVO matterAddVO) {

        String usreId = TokenUtil.getTokenUserBId();
//        String usreId = "1";

        Matter matter = new Matter();
        matterAddVO.setCreateBy(usreId);
        matterAddVO.setCreateTime(LocalDateTime.now());
        //matterAddVO.setTuiBId(UUID.randomUUID().toString().replaceAll("-", "").toUpperCase());//todo：生成全局唯一ID
        matterAddVO.setUpdateBy(usreId);
        matterAddVO.setTaskTitle("");
        matterAddVO.setIsDel(false);
        matterAddVO.setUpdateTime(LocalDateTime.now());
        matterAddVO.setTuiBId(usreId);
//        matter.setRemind(false);


        BeanUtils.copyProperties(matterAddVO,matter);
        QueryWrapper<Matter> matterQueryWrapper = new QueryWrapper<>();
        matterQueryWrapper.setEntity(matter);
        String a = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();

        matter.setbId(a);
//        List<Matter> matters = baseMapper.selectList(matterQueryWrapper);
//        if (!CollectionUtils.isEmpty(matters)){
//            throw new ToException(2001,"已有记录，增加失败");
//        }

        baseMapper.insert(matter);
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("b_id",a);
        Matter matter1 = baseMapper.selectOne(queryWrapper);
        matterAddVO.setId(String.valueOf(matter1.getId()));


    }

    @Override
    public void deleteInfo(MatterAddVO matterAddVO) {
        Matter matter = new Matter();
        matter.setbId(matterAddVO.getId());
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",matterAddVO.getId());
        queryWrapper.eq("tui_b_id",TokenUtil.getTokenUserBId());
//        queryWrapper.eq("tui_b_id","1");
        Matter matterInfo = baseMapper.selectOne(queryWrapper);
        if (matterInfo == null){
            throw new ToException(2001,"记录不存在");
        }
        this.remove(queryWrapper);
    }

    @Override
    public void updateInfo(MatterAddVO matterAddVO) {
        matterAddVO.setId(matterAddVO.getId());
        matterAddVO.setTaskContent(matterAddVO.getText());

        String userId = TokenUtil.getTokenUserBId();
//        String userId = "1";
        Matter matterInfo = baseMapper.selectById(matterAddVO);
        if (matterInfo == null){
            throw new ToException(2001,"记录不存在");
        }
        Matter matter = new Matter();

        matterInfo.setTaskContent(matterAddVO.getText());

        BeanUtils.copyProperties(matterInfo,matter);
        matter.setUpdateBy(userId);
        matter.setUpdateTime(LocalDateTime.now());
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(matter);
        baseMapper.updateById(matter);
    }

    @Override
    public void finishInfo(MatterAddVO matterAddVO) {
        String userBId = TokenUtil.getTokenUserBId();
//        String userBId = "1";
        String matterBId = matterAddVO.getId();
        QueryWrapper<Matter> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Matter::getId, matterBId);
        wrapper.lambda().eq(Matter::getTuiBId, userBId);
        // 查询事项
        Matter matterInfo = baseMapper.selectOne(wrapper);
        if (matterInfo == null) {
            throw new ToException(2001, "记录不存在！");
        }
        if (TodoListConstant.TASK_STATUS_COMPLETE == matterInfo.getTaskStatus()) {
            throw new ToException(2002, "该待办事项已完成！");
        }
        UpdateWrapper<Matter> uWrapper = new UpdateWrapper<>();
        uWrapper.lambda().eq(Matter::getId, matterBId);
        uWrapper.lambda().eq(Matter::getTuiBId, userBId);
        Matter uMatter = new Matter();
        uMatter.setTaskStatus(TodoListConstant.TASK_STATUS_COMPLETE);
        // 更新事项的状态为完成
        baseMapper.update(uMatter, uWrapper);
    }

    @Override
    public List<Matter> getExpireMatter(Date date) {
        QueryWrapper<Matter> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Matter::getRemind, 1);
        wrapper.lambda().eq(Matter::getPlanCompletionTime, DateUtil.clearTime(date));
        List<Matter> matterList = baseMapper.selectList(wrapper);
        return matterList;
    }

    @Override
    public void timedTask() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        System.out.println(simpleDateFormat.format(DateUtil.clearTime(now)));
        List<TimedTaskVO> list = matterMapper.selectMatterList(simpleDateFormat.format(DateUtil.clearTime(now)),
                simpleDateFormat.format(DateUtil.addOneDay(now)));
        Map<String, List<TimedTaskVO>> map = list.stream().collect(Collectors.groupingBy(TimedTaskVO::getTuiBId));

        // 发送邮件的内容
        String title = "TODOList待办事项到期提醒";
        String contentTemplate = "TODOList用户%s您好！您设置的待办事项[%s]今天到期！";
        long start = System.currentTimeMillis();
        map.forEach(new BiConsumer<String, List<TimedTaskVO>>() {
            @Override
            public void accept(String s, List<TimedTaskVO> timedTaskVOS) {
                if (timedTaskVOS != null && !timedTaskVOS.isEmpty()) {
                    String email = timedTaskVOS.get(0).getEmail();
                    asyncSendMail(new String[]{email}, title, String.format(contentTemplate, s, timedTaskVOS));
                }
            }
        });
//        for (TimedTaskVO matter : list) {
//            String taskContent = matter.getTaskTitle()+": "+matter.getTaskContent();
//            String emailContent = String.format(contentTemplate, matter.getUserName(), taskContent);
//            // todo 数据量大的时候会怎么样 测试
//            asyncSendMail(new String[]{matter.getEmail()}, title, emailContent);
//        }
        long end = System.currentTimeMillis();
        System.out.println("所用时间：" + (end - start));
    }

    public void timedTask2() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();

        List<TimedTaskVO> list = matterMapper.selectMatterList2(simpleDateFormat.format(DateUtil.clearTime(now)),
                simpleDateFormat.format(DateUtil.addOneDay(now)), simpleDateFormat.format(now),
                simpleDateFormat.format(DateUtil.addTowHour(now)));
        Map<String, List<TimedTaskVO>> map = list.stream().collect(Collectors.groupingBy(TimedTaskVO::getTuiBId));

        // 发送邮件的内容
        String title = "TODOList待办事项到期提醒";
        String contentTemplate = "TODOList用户%s您好！您设置的待办事项[%s]今天到期！";
        long start = System.currentTimeMillis();
        map.forEach(new BiConsumer<String, List<TimedTaskVO>>() {
            @Override
            public void accept(String s, List<TimedTaskVO> timedTaskVOS) {
                if (timedTaskVOS != null && !timedTaskVOS.isEmpty()) {
                    String email = timedTaskVOS.get(0).getEmail();
                    asyncSendMail(new String[]{email}, title, String.format(contentTemplate, s, timedTaskVOS));
                }
            }
        });
        long end = System.currentTimeMillis();
        System.out.println("所用时间：" + (end - start));
    }

    @Async
    public void asyncSendMail(String[] to, String title, String content) {
        taskExecutor.execute(()->{
            mailService.sendSimpleMail(to, title, content);
        });
    }

    @Override
    public List<Matter> getListInfo(MatterVO matterVO) {
        QueryWrapper<Matter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del",0);
//        if (!StringUtils.isEmpty(matterVO.getBId())){
//            queryWrapper.eq("b_id",matterVO.getBId());
//        }



        if (!StringUtils.isEmpty(matterVO.getTaskStatus())){
            queryWrapper.eq("task_status",matterVO.getTaskStatus());
        }
        queryWrapper.eq("tui_b_id",TokenUtil.getTokenUserBId());
//        queryWrapper.eq("tui_b_id","1");
        baseMapper.selectList(queryWrapper);
        return baseMapper.selectList(queryWrapper);
    }
}
